package com.dataStructures.sort;

import java.util.Arrays;

/**
 * test class
 *
 * @author zcq
 */
public class Test {
	public static void main(String[] args) {
		int[] arr = {3, 9, -1, 10, 20};
		System.out.println("排序前：" + Arrays.toString(arr));
		insertSort(arr);
		System.out.println("排序后：" + Arrays.toString(arr));
	}

	private static void insertSort(int[] arr) {
		int insertVal;
		int insertIndex;

		// 从第二个数开始，依次寻找插入位置
		for (int i = 1; i < arr.length; i++) {
			insertVal = arr[i];
			insertIndex = i - 1;
			while (insertIndex > 0 && insertVal < arr[insertIndex]) {
				// 把前边一个数的位置后移
				arr[insertIndex + 1] = arr[insertIndex];
				insertIndex--;
			}
			if (insertIndex + 1 != i) {
				arr[insertIndex + 1] = insertVal;
			}
		}
	}
}
